﻿function _ismb() { if ((navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|iOS|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i))) { return true; } else { return false; } }
function _getreq(n){var reg=new RegExp("(^|&)"+n+"=([^&]*)(&|$)","i");var r=window.location.search.substr(1).match(reg);if(r!=null){return unescape(r[2])}return null};
Date.Parse = function (date) {
	return eval('new ' + date.replace('/', '', 'g').replace('/', '', 'g'));
};
Date.prototype.Format = function (format) {
	var o =
		{
			"M+": this.getMonth() + 1, //month
			"d+": this.getDate(),    //day
			"h+": this.getHours(),   //hour
			"m+": this.getMinutes(), //minute
			"s+": this.getSeconds(), //second
			"q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
			"S": this.getMilliseconds() //millisecond
		}
	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
	return format;
};


function calculateMA(dayCount, data) { var result = []; for (var i = 0, len = data.length; i < len; i++) { if (i < dayCount) { result.push('-'); continue; } var sum = 0; for (var j = 0; j < dayCount; j++) { sum += data[i - j][1]; } result.push((sum / dayCount).toFixed(5)); } return result; }

function getChartDateStr(tick) {
    var ordate = new Date(tick * 1000);
    if (_chartperiod.indexOf("1M") == 0 || _chartperiod.indexOf("5M") == 0 || _chartperiod.indexOf("15M") == 0 || _chartperiod.indexOf("30M") == 0) { return ordate.Format("yyyy-MM-dd hh:mm"); }
    else if (_chartperiod.indexOf("1H") == 0 || _chartperiod.indexOf("4H") == 0) { return ordate.Format("yyyy-MM-dd hh:mm"); }
    else return ordate.Format("yyyy-MM-dd");
}
function fixChartDateStr(datestr) {
    if ("D,W,M".indexOf(_chartperiod) >= 0) {
        if (datestr.length > 10) { return datestr.substr(0, 10); }
    }
    else
    { if (datestr.length > 16) { return datestr.substr(0, 16); } }

    return datestr;
}

function PrefixInteger(num, n) {
	return (Array(n).join(0) + num).slice(-n);
}

function reqchart(symbol, period) {
    var isnew = (_chartsymbol != symbol || _chartperiod != period);
    _chartsymbol = symbol;
    _chartperiod = period;
    if (isnew) { datareset(); }
    KKE.api("datas.ecd.chart", [symbol, period, isnew],
        function(d) {
            if (d.c == 0) {
                fixdata(d.d);
            }
        }
    );
}
function reqlist(symbols,callback) {
    KKE.api("datas.ecd.wssub", [symbols],
        function(d) {
            if (d.c == 0) {
				if (callback) { callback(d.d); }
				if (d.d.fsymbol == _chartsymbol) {
					fixdata([{ d: fixChartDateStr(d.d.date), o: 0, h: 0, l: 0, c: d.d.price, v: 0 }]);
                }
            }
        }
    );
}

var _chartlstp = 0;
var _chartperiod = "";
var _chartsymbol = "";
var _dates = [];
var _data = [];
var _datal = [];
var _volumes = [];
function datareset() {
    _dates = [];
    _data = [];
    _datal = [];
    _volumes = [];
}
function fixdata(datas) {

    if (datas.length==undefined || datas.length <= 0) {
		return;
	}
	//dstr标准为yyyy-MM-dd HH:mm
    if (datas.length == 1) {
        var dstr = fixChartDateStr(datas[0].d); 
		//减少渲染次数
        if (_dates.length > 0 && _dates[_dates.length - 1] <= dstr && datas[0].c != _chartlstp) {
            datas[0].d = _dates[_dates.length - 1];
			if (datas[0].o <= 0) { datas[0].o = _data[_dates.length - 1][0]; }
			if (datas[0].l <= 0) { datas[0].l = _data[_dates.length - 1][2]; }
			if (datas[0].h <= 0) { datas[0].h = _data[_dates.length - 1][3]; }
			if (datas[0].v <= 0) { datas[0].v = _data[_dates.length - 1][4]; }
		}
		else { return; }
	}

	if (_dates.length > 0) {
		//最小
        var dstr = fixChartDateStr(datas[0].d);

		while (_dates[_dates.length - 1] >= dstr) {
			_dates.splice(_dates.length - 1);
			_data.splice(_data.length - 1);
			_datal.splice(_datal.length - 1);
			_volumes.splice(_volumes.length - 1);
		}
	}

    for (var i = 0; i <= (datas.length - 1); i++) {
        var d = datas[i];
		if (d.c <= 0)
            continue;

        if (i == (datas.length - 1))
            _chartlstp = d.c;

        var dstr = fixChartDateStr(d.d);
		_dates.push(dstr);
        _data.push([parseFloat(d.o), parseFloat(d.c), parseFloat(d.l), parseFloat(d.h), parseInt(d.v)]);
        _datal.push(parseFloat(d.c));
        _volumes.push(parseInt(d.v));
	}

	render();
}

function render() {
	var dataMA5 = calculateMA(5, _data);
	var dataMA20 = calculateMA(20, _data);
	var dataMA30 = calculateMA(30, _data);

	//记录之前的状态
	if (_myChart && _myChart.getOption()) {
		_dzst = _myChart.getOption().dataZoom[0].start;
		_dzed = _myChart.getOption().dataZoom[0].end;
	}
	else {
		if (_dates.length < _stnum)
			_dzst = 0;
		else {
			_dzst = (_dates.length - _stnum) * 100 / _dates.length;
		}
		_dzed = 100;
	}

	var option = createOption(__symbol, _mtype, _sets, __period, _dzst, _dzed, _dates, _data, _datal, _volumes, dataMA5, dataMA20, dataMA30);

	if (option && typeof option === "object") {
		_myChart.setOption(option, true);
	}

}

function createOption(symbol, ltype, colorset, period, stp, edp, dates, datas, datals, vols, dataMA5, dataMA20, dataMA30)
{
    var labelFont = '12px Sans-serif';
    return {
        backgroundColor: colorset.bg,
        animation: false,
        color: colorset.cls,
        title: {
            show: false
        },
        legend: {
            top: 0,
            data: (ltype == "line" ? [symbol + "," + period] : [symbol + "," + period, 'MA5', 'MA20', 'MA30']),
            textStyle: {
                color: colorset.l1
            }
        },
        tooltip: {
            transitionDuration: 0,
            confine: true,
            bordeRadius: 4,
            borderWidth: 1,
            borderColor: colorset.tpl,
            backgroundColor: colorset.tpb,
            textStyle: {
                fontSize: 12,
                color: colorset.tpt
            },
            position: function (pos, params, el, elRect, size) {
                var obj = {
                    top: colorset.frametop
                };
                obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
                return obj;
            },
            formatter(param) {
                if (param[0] == undefined) { return ""; }
                if (ltype == "line") {
                    return [param[0].name, 'C: ' + param[0].data.toFixed(5)].join('<br/>');
                }
                else {
                    return [param[0].name,
                    'O: ' + param[0].data[1].toFixed(5),
                    'C: ' + param[0].data[2].toFixed(5),
                    'L: ' + param[0].data[3].toFixed(5),
                    'H: ' + param[0].data[4].toFixed(5),
                    'V: ' + param[0].data[5].toFixed(0)].join('<br/>');
                }
            }
        },
        axisPointer: {
            link: [{
                xAxisIndex: [0, 1]
            }]
        },
        dataZoom: [{
			type: 'slider',
			xAxisIndex: [0, 1],
                start: stp,
                end: edp
            },
            {
                type: 'inside',
                xAxisIndex: [0, 1],
                start: stp,
                end: edp
        }],
        xAxis: [{
            type: 'category',
            data: dates,
            boundaryGap: false,
            axisLine: { lineStyle: { color: colorset.l2, opacity: 0.1, width: 0.1 } },
            axisLabel: {
                formatter: function (value) {
                    return value;
                }
            },
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
                show: true
            }
        }, {
            type: 'category',
            gridIndex: 1,
            data: dates,
            scale: true,
            boundaryGap: false,
            splitLine: { show: false },
            axisLabel: { show: false },
            axisTick: { show: false },
            axisLine: { lineStyle: { color: colorset.l2, opacity: 0.1, width: 0.1 } },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
                type: 'shadow',
                label: { show: false },
                triggerTooltip: true
            }
        }],
        yAxis: [{
            scale: true,
            splitNumber: 2,
            axisLine: { lineStyle: { color: colorset.l2 } },
            splitLine: { show: true },
            axisTick: { show: false },
            axisLabel: {
                inside: true,
                formatter: '{value}\n'
            }
        }, {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLabel: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false }
        }],
        grid: [{
            left: colorset.lp,
            right: colorset.rp,
            top: colorset.frametop,
            height: colorset.h
        }, {
                left: colorset.lp,
                right: colorset.rp,
                height: colorset.h2,
            top: (colorset.frametop + colorset.h + 20)
        }],
        graphic: [{
            type: 'group',
            left: 'center',
            bounding: 'raw',
            children: [{
                id: 'MA5',
                type: 'text',
                style: { fill: colorset.cls[1], font: labelFont },
                left: 0
            }, {
                id: 'MA20',
                type: 'text',
                style: { fill: colorset.cls[2], font: labelFont },
                left: 'center'
            }, {
                id: 'MA30',
                type: 'text',
                style: { fill: colorset.cls[3], font: labelFont },
                right: 0
            }]
        }],
        series: [{
            name: '量',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            itemStyle: {
                normal: {
                    color: colorset.v
                },
                emphasis: {
                    color: colorset.v0
                }
            },
            data: vols,
            tooltip: {
                formatter(param) {
                    return [param.name, 'V: ' + param.value].join('<br/>');
                }
            }
        },
        {
			type: ltype,
			symbol: "none",
            name: (symbol + "," + period),
            data: (ltype == "line" ? datals : datas),
            itemStyle: {
                normal: {
                    color: (ltype == "line" ? colorset.l2 : colorset.up),
                    color0: colorset.dn,
                    borderColor: (ltype == "line" ? colorset.l1 : colorset.up1),
                    borderColor0: colorset.dnl
                },
                emphasis: {
                    color: colorset.up0,
                    color0: colorset.dn0,
                    borderColor: colorset.up0,
                    borderColor0: colorset.dn0
                }
            },
            areaStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: "#B0C4DE"
                    }, {
                        offset: 1,
                        color: "#A9A9A9"
                    }])
                }
            },
            tooltip: {
                formatter(param) {
                    if (ltype == "line") {
                        return [param.name, 'C: ' + param.data.toFixed(5)].join('<br/>');
                    }
                    else {
                        return [param.name,
                            'O: ' + param.data[1].toFixed(5),
                            'C: ' + param.data[2].toFixed(5),
                            'L: ' + param.data[3].toFixed(5),
                            'H: ' + param.data[4].toFixed(5),
                            'V: ' + param.data[5].toFixed(0)].join('<br/>');
                    }
                }
            }, markLine: {
                symbol: "none",
                silent: true,
                label: {show:true},
                lineStyle: { opacity :0.5,width:0.3},
                data: [
                    {
                        //yAxis: (ltype == "line" ? (datals.length > 0 ? datals[datals.length - 1] : 0) : (datas.length > 0 ? datas[datas.length - 1][1] : 0))
                        yAxis: (datas.length > 0 ? datas[datas.length - 1][1].toFixed(5) : 0)
                    }
                ]
            }
        }, {
            name: 'MA5',
            type: 'line',
                data: (ltype == "line" ? null : dataMA5),
            smooth: true,
            showSymbol: false,
            lineStyle: {
                normal: {
                    width: 0.6,
                    opacity: 0.7
                }
            },
            tooltip: {
                formatter(param) {
                    return [param.name, 'MA5: ' + parseFloat(param.value).toFixed(2)].join('<br/>');
                }
            }
        }, {
            name: 'MA20',
            type: 'line',
                data: (ltype == "line" ? null : dataMA20),
            smooth: true,
            showSymbol: false,
            lineStyle: {
                normal: {
                    width: 0.6,
                    opacity: 0.7
                }
            },
            tooltip: {
                formatter(param) {
                    return [param.name, 'MA20: ' + parseFloat(param.value).toFixed(2)].join('<br/>');
                }
            }
        }, {
            name: 'MA30',
            type: 'line',
                data: (ltype=="line"?null:dataMA30),
            smooth: true,
            showSymbol: false,
            lineStyle: {
                normal: {
                    width: 0.6,
                    opacity: 0.7
                }
            },
            tooltip: {
                formatter(param) {
                    return [param.name, 'MA30: ' + parseFloat(param.value).toFixed(2)].join('<br/>');
                }
            }
        }]
    };
}

